//
//  ZCAdjustmentLocationViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/7.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCAdjustmentLocationViewController.h"
#import "ZCAdjustmentTableViewCell.h"
#import "ZCAdjustmentModel.h"



static NSString *adjustmentCellID = @"ZCAdjustmentTableViewCell";

@interface ZCAdjustmentLocationViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) ZCLocationModel *locationModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCAdjustmentLocationViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCAdjustmentTableViewCell class] forCellReuseIdentifier:adjustmentCellID];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _tableView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, space(522), 30)];
        _searchBar.placeholder = @"请输入库位号";
        _searchBar.delegate = self;
        _searchBar.keyboardType = UIKeyboardTypeASCIICapable;
    }
    return _searchBar;
}

- (NSMutableArray *)listArray {
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, space(522), 30)];
    [titleView addSubview:self.searchBar];
    self.navigationItem.titleView = titleView;
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton setTitleColor:ZCColor(0x000000, 0.87) forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] init]];
    [self.view addSubview:self.tableView];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.searchBar becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 网络请求
- (void)loadData {
    self.currentPage = 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    [param setObject:houseId forKey:@"houseId"];
    [param setObject:self.searchBar.text forKey:@"key"];
    [param setObject:@(self.currentPage) forKey:@"current"];
    [param setObject:@(10) forKey:@"size"];
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:AdjustmentLocation params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                [weakSelf.listArray removeAllObjects];
                weakSelf.locationModel = [ZCLocationModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.listArray addObjectsFromArray:weakSelf.locationModel.records];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                if (weakSelf.locationModel.records.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
            }else {
                [weakSelf.tableView.mj_header endRefreshing];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

- (void)loadMoreData {
    self.currentPage++;
    if (self.currentPage <= [self.locationModel.pages integerValue]) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
        [param setObject:houseId forKey:@"houseId"];
        [param setObject:self.searchBar.text forKey:@"key"];
        [param setObject:@(self.currentPage) forKey:@"current"];
        [param setObject:@(10) forKey:@"size"];
        

        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:AdjustmentLocation params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    weakSelf.locationModel = [ZCLocationModel yy_modelWithDictionary:responseObject[@"data"]];
                    [weakSelf.listArray addObjectsFromArray:weakSelf.locationModel.records];
                    [weakSelf.tableView reloadData];
                    if (weakSelf.locationModel.records.count < 10) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                }else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                    weakSelf.currentPage--;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.hud showAnimated:YES];
                        weakSelf.hud.mode = MBProgressHUDModeText;
                        weakSelf.hud.label.text = responseObject[@"message"];
                        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                    });
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                [weakSelf.tableView.mj_footer endRefreshing];
                weakSelf.currentPage--;
            }];
        });
    }else {
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - 按钮点击
- (void)backClick:(UIButton *)sender {
    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self loadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCAdjustmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:adjustmentCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ZCLocationInfoModel *infoModel = self.listArray[indexPath.section];
    cell.locationInfoModel = infoModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(100);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCLocationInfoModel *infoModel = self.listArray[indexPath.section];
    if (_locationBlock) {
        _locationBlock([NSString stringWithFormat:@"%@ %@",infoModel.storeAreaName, infoModel.name], infoModel.Id);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
